package cn.wx.autoconfiguration;

import cn.wx.DefaultWxMpConfigStorageFactory;
import cn.wx.WxMpConfigStorageFactory;
import cn.wx.WxMpServiceRegisterPostProcessor;
import cn.wx.properties.WxMpProperties;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import static cn.wx.properties.WxMpProperties.PREFIX;


@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(WxMpProperties.class)
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", havingValue = "true", matchIfMissing = true)
public class WxMpAutoConfiguration {

    private final WxMpProperties properties;

    private final WxMpConfigStorageFactory wxMpConfigStorageFactory;

    @Bean
    @Primary
    @ConditionalOnMissingBean(name = "wxMpService")
    public WxMpService wxMpService() {
        WxMpService service = new WxMpServiceHttpClientImpl();
        service.setMultiConfigStorages(wxMpConfigStorageFactory.create(), properties.getName());
        return service;
    }


    @Bean
    @ConditionalOnMissingBean
    public WxMpConfigStorageFactory wxMpConfigStorageFactory() {
        return new DefaultWxMpConfigStorageFactory(properties);
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxMpServiceRegisterPostProcessor")
    public WxMpServiceRegisterPostProcessor wxMpServiceRegisterPostProcessor(WxMpService wxMpService) {
        return new WxMpServiceRegisterPostProcessor(properties, wxMpService);
    }
}
